<?php

include("includes/theme-options.php");

# Sidebar
if (function_exists('register_sidebar'))
{
    register_sidebar(array(
		'name'			=> 'Widget bên trái của Trang chủ',
        'before_widget'	=> '',
        'after_widget'	=> '</div>',
        'before_title'	=> '<h3>',
        'after_title'	=> '</h3><div class="box">',
    ));	
	
    register_sidebar(array(
		'name'			=> 'Widget bên phải của Trang chủ',
        'before_widget'	=> '',
        'after_widget'	=> '</div>',
        'before_title'	=> '<h3>',
        'after_title'	=> '</h3><div class="box">',
    ));		
	
    register_sidebar(array(
		'name'			=> 'Widget bên trái của trang',
        'before_widget'	=> '',
        'after_widget'	=> '</div>',
        'before_title'	=> '<h3>',
        'after_title'	=> '</h3><div class="box">',
    ));	
	
    register_sidebar(array(
		'name'			=> 'Widget bên phải của trang',
        'before_widget'	=> '',
        'after_widget'	=> '</div>',
        'before_title'	=> '<h3>',
        'after_title'	=> '</h3><div class="box">',
    ));	
}

# Limit Post
function the_content_limit($max_char, $more_link_text = '', $stripteaser = 0, $more_file = '') {
    $content = get_the_content($more_link_text, $stripteaser, $more_file);
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);
    $content = strip_tags($content);

   if (strlen($_GET['p']) > 0) {
      echo "";
      echo $content;
      echo "&nbsp;<a href='";
      the_permalink();
      echo "'>"."Chi tiết &rarr;</a>";
      echo "";
   }
   else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {
        $content = substr($content, 0, $espacio);
        $content = $content;
        echo "";
        echo $content;
        echo "...";
        echo "&nbsp;<a href='";
        the_permalink();
        echo "'>"."</a>";
        echo "";
   }
   else {
      echo "";
      echo $content;
      echo "&nbsp;<a href='";
      the_permalink();
      echo "'>"."Chi tiết &rarr;</a>";
      echo "";
   }
}

# Turn a category ID to a Name
function cat_id_to_name($id) {
	foreach((array)(get_categories()) as $category) {
    	if ($id == $category->cat_ID) { return $category->cat_name; break; }
	}
}

# Get image attachment (sizes: thumbnail, medium, full)
function get_thumbnail($postid=0, $size='full') {
	if ($postid<1) 
	$postid = get_the_ID();
	$thumb = get_post_meta($postid, "thumb", TRUE); // Declare the custom field for the image
	if ($thumb != null or $thumb != '') {
		echo $thumb; 
	}
	elseif ($images = get_children(array(
		'post_parent' => $postid,
		'post_type' => 'attachment',
		'numberposts' => '1',
		'post_mime_type' => 'image', )))
		foreach($images as $image) {
			$thumbnail=wp_get_attachment_image_src($image->ID, $size);
			?>
<?php echo $thumbnail[0]; ?>
<?php
		}
	else {
		echo get_bloginfo ( 'stylesheet_directory' );
		echo '/images/image-pending.gif';
	}
	
}

# Automatically display/resize thumbnail
function tj_thumbnail($width, $height) {
?>

<a href="<?php the_permalink() ?>" rel="bookmark"> <img src="<?php bloginfo('template_directory'); ?>/includes/timthumb.php?src=<?php get_thumbnail($post->ID, 'full'); ?>&amp;h=<?php echo get_theme_mod($height); ?>&amp;w=<?php echo get_theme_mod($width); ?>&amp;zc=1" alt="<?php the_title(); ?>" /> </a>
<?php
}

# Breadcrumb
function the_breadcrumb() {
	if (!is_home()) {
		echo '<a href="';
		echo get_option('home');
		echo '">';
		echo "Trang chủ";
		echo "</a> &raquo; ";
		if (is_category() || is_single()) {
			single_cat_title();
			if (is_single()) {
			the_category(', ');
				echo " &raquo; ";
				the_title();
			}
		} elseif (is_page()) {
			echo the_title();
		}
		  elseif (is_tag()) {
			echo 'Các bài viết được gắn với từ khóa:  "'; 
			single_tag_title();
			echo '"'; }
		elseif (is_day()) {echo "Lưu trữ theo "; the_time(' F jS, Y');}
		elseif (is_month()) {echo "Lưu trữ theo "; the_time(' F, Y');}
		elseif (is_year()) {echo "Lưu trữ theo "; the_time(' Y');}
		elseif (is_author()) {echo "Tác giả lưu trữ";}
		elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "Các lưu trữ blog";}
		elseif (is_search()) {echo "Kết quả search";}
	}
}

# Most Comment
function mdv_most_commented($no_posts = 5, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
    global $wpdb;
	
	$mdv_most_commented = wp_cache_get('mdv_most_commented');
	if ($mdv_most_commented === false) {
		$request = "SELECT ID, post_title, comment_count FROM $wpdb->posts";
		$request .= " WHERE post_status = 'publish'";
		if (!$show_pass_post) $request .= " AND post_password =''";
	
		if ($duration !="") $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
	
		$request .= " ORDER BY comment_count DESC LIMIT $no_posts";
		$posts = $wpdb->get_results($request);

		if ($posts) {
			foreach ($posts as $post) {
				$post_title = htmlspecialchars($post->post_title);
				$comment_count = $post->comment_count;
				$permalink = get_permalink($post->ID);
				$mdv_most_commented .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a>' . $after;
			}
		} else {
			$mdv_most_commented .= $before . "Không tìm thấy" . $after;
		}
	
		wp_cache_set('mdv_most_commented', $mdv_most_commented);
	} 

    echo $mdv_most_commented;
}

/**
 * Hooks the WP cpt_post_types filter 
 *
 * @param array $post_types An array of post type names that the templates be used by
 * @return array The array of post type names that the templates be used by
 **/
function my_cpt_post_types( $post_types ) {
    $post_types[] = '1 cột';
    $post_types[] = '2 cột';
    return $post_types;
}
add_filter( 'cpt_post_types', 'my_cpt_post_types' );

if(!function_exists('postListByCategory'))
	{
		function categoryNameByCategoryID($categoryID = 0)
		{
			global $wpdb;
			$sqlQuery = 'SELECT name FROM ' . $wpdb->prefix . "terms WHERE term_id=$categoryID";
			return $wpdb->get_var($sqlQuery);
		}
	}

    if(!function_exists('postListByCategory'))
	{
		function postListByCategorySlug($slug = '')
        {
            $category = get_term_by( 'slug', $slug, 'category' );
            if ( $category )
                _make_cat_compat( $category );
           $posts = get_posts(array('numberposts' => 5, 'category__in' => array($category->cat_ID)));
           $outputString = '';
           $outputString .= '<ul>' . chr(10);
           
            if (count($posts) > 0) {
                foreach ($posts as $post) {
                $permaLink = get_permalink();
				$permaLink = trim($permaLink);
				if(!empty($permaLink))
				{
					$outputString .= '<li>' . chr(10);
					$outputString .= '<a href="' . get_permalink() . '">' . get_the_title($post->ID) . '</a>&nbsp;' . chr(10);
					$outputString .= '<small>&nbsp;<i>Vào lúc: ' . get_the_time('Y/m/d H:i:s') .'</i></small>' . chr(10);
					$outputString .= '</li>' . chr(10);
				}
                }
                $outputString .= '</ul>' . chr(10);
            }
            else {
                $outputString = "<div style='text-align:center;margin-bottom:10px;'>Hiện tại chưa có thông tin.</div>";
            }
           
            
            return $outputString;
        }
    }
	if(!function_exists('postListByCategory'))
	{
		function postListByCategoryID($categoryID = 0)
		{
			$outputString = '';
			query_posts('orderby=name&amp;order=asc&amp;cat=' . $categoryID . '&amp;showposts=5');
			$outputString .= '<ul>' . chr(10);
			while (have_posts()) : the_post();
				$permaLink = get_permalink();
				$permaLink = trim($permaLink);
				if(!empty($permaLink))
				{
					$outputString .= '<li>' . chr(10);
					$outputString .= '<a href="' . get_permalink() . '">' . get_the_title($post->ID) . '</a><br />' . chr(10);
					$outputString .= '<small>' . get_the_time('D M jS Y') .'</small>' . chr(10);
					$outputString .= '</li>' . chr(10);
				}
			endwhile;
			$outputString .= '</ul>' . chr(10);
			return $outputString;
		}
	}